package liurong.driver.thread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import org.junit.Test;

public class Lock1Test {
	private static final Lock lock = new ReentrantLock();

	private CountDownLatch countDownLatch = new CountDownLatch(1);

	private Map<String, HashMap<Lock, CountDownLatch>> lockMap = new ConcurrentHashMap<String, HashMap<Lock, CountDownLatch>>();

	@Test
	public void test() throws Exception {
		for (int i = 0; i < 10; i++) {
			int j = i;
			new Thread(() -> {
				int group = j % 3;
				process(group);
			}).start();
		}
		TimeUnit.SECONDS.sleep(10);
		System.in.read();
	}

	private void process(int group) {
		System.out.println(Thread.currentThread().getName() + "我是第 " + group + " 组");
		try {
			if (lock.tryLock()) {
				try {
					System.out.println("主线程睡眠开始");
					TimeUnit.SECONDS.sleep(5);
					System.out.println("主线程睡眠结束");
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					lock.unlock();
					countDownLatch.countDown();
				}
			} else {
				System.out.println("等待开始" + Thread.currentThread().getName());
				countDownLatch.await();
				System.out.println("等待结束" + Thread.currentThread().getName());
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

}
